package com.qmock.pay.security;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMReader;
import org.bouncycastle.openssl.PasswordFinder;

import java.io.*;
import java.security.KeyPair;
import java.security.PublicKey;
import java.security.Security;

/**
 * @author tianqing.wang
 */
public class PEMRsa {

    public static PublicKey getPublicKeyFromPEM(File file, final String password) throws Exception {
        try {
            byte[] bytes= getByte(file);
            Security.addProvider(new BouncyCastleProvider());
            ByteArrayInputStream byteArrayInputStream=new ByteArrayInputStream(bytes);
            PEMReader pemReader=new PEMReader(new InputStreamReader(byteArrayInputStream),new PasswordFinder() {
                @Override
                public char[] getPassword() {
                    return password.toCharArray();  //To change body of implemented methods use File | Settings | File Templates.
                }
            });
            KeyPair keyPair = (KeyPair) pemReader.readObject();
            pemReader.close();
            PublicKey pubk = keyPair.getPublic();
            return pubk;
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("获取公钥的时候出现了bug");
        }
    }
    /**
     * 把一个文件转化为字节
     * @param file
     * @return   byte[]
     * @throws Exception
     */
    public static byte[] getByte(File file) throws Exception
    {
        byte[] bytes = null;
        if(file!=null)
        {
            InputStream is = new FileInputStream(file);
            int length = (int) file.length();
            if(length>Integer.MAX_VALUE)   //当文件的长度超过了int的最大值
            {
                System.out.println("this file is max ");
                return null;
            }
            bytes = new byte[length];
            int offset = 0;
            int numRead = 0;
            while(offset<bytes.length&&(numRead=is.read(bytes,offset,bytes.length-offset))>=0)
            {
                offset+=numRead;
            }
            //如果得到的字节长度和file实际的长度不一致就可能出错了
            if(offset<bytes.length)
            {
                System.out.println("file length is error");
                return null;
            }
            is.close();
        }
        return bytes;
    }

}
